// stores/cart.js

import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useCartStore = defineStore('cart', () => {
	// 购物车数据
	const cartData = ref([])

	// 添加刷新标记
	const needRefresh = ref(false)

	// 合计件数
	const totalCount = computed(() => {
		return cartData.value.reduce((sum, item) => sum + item.num, 0)
	})

	// 总价格
	const totalPrice = computed(() => {
		return cartData.value.reduce((sum, item) => sum + (item.num * item.buy_price), 0)
	})

	// 添加商品到购物车
	const addToCart = (products) => {
		products.forEach(product => {
			const existingItem = cartData.value.find(item => item.pro_id === product.pro_id)
			if (existingItem) {
				existingItem.num += product.num
			} else {
				cartData.value.push(product)
			}
		})
	}

	// 更新商品数量
	const updateQuantity = (pro_id, newNum) => {
		const item = cartData.value.find(item => item.pro_id === pro_id)
		if (item && newNum > 0) {
			item.num = newNum
		}
	}

	// 移除购物车中的商品
	const removeFromCart = (pro_id) => {
		cartData.value = cartData.value.filter(item => item.pro_id !== pro_id)
	}

	// 清空购物车
	const clearCart = () => {
		cartData.value = []
	}

	// 设置刷新标记
	const setNeedRefresh = (value) => {
		needRefresh.value = value
	}

	return {
		cartData,
		totalCount,
		totalPrice,
		addToCart,
		updateQuantity,
		removeFromCart,
		clearCart,
		needRefresh,
		setNeedRefresh
	}
}, {
	persist: {
		storage: {
			getItem(key) {
				return uni.getStorageSync(key)
			},
			setItem(key, value) {
				uni.setStorageSync(key, value)
			},
		},
	},
})